<?php

namespace api\controllers;


use api\components\BaseController;
use common\helpers\commonApi;
use common\helpers\JwtApi;
use common\models\System;
use common\models\User;
use EasyWeChat\Factory;
use Yii;

class LoginController extends BaseController
{
    public function actionLogin()
    {
        $params = Yii::$app->request->post();
        $code = $params['code'] ?? '';
        $rawData = $params['data'] ?? '';
        $mark = $params['mark'] ?? '';
        if ($mark){
            $data['unionid'] = '';
            $data['openid'] = $mark;
        }else{
            if (!$code){
                return commonApi::message('请授权！',false);
            }
            $wechat = json_decode($rawData, true);
            if (!$wechat) {
                return commonApi::message('数据错误！',false);
            }
            $system = System::getModel();
            if (!$system||!$system->a_appid||!$system->a_secret){
                return commonApi::message('请配置小程序',false);
            }
            $config = [
                'app_id' => $system->a_appid,
                'secret' => $system->a_secret,
                'response_type' => 'array',
            ];
            try {
                $app = Factory::miniProgram($config);
            }catch (\Throwable $e){
                return commonApi::message($e->getMessage(),false);
            }catch (\Exception $e){
                return commonApi::message($e->getMessage(),false);
            }
            $data = $app->auth->session($code);
            //判断code是否过期
            if (isset($data['errcode'])) {
                return commonApi::message('code已过期或不正确',false);
            }
        }
        $weappOpenid = $data['openid'];
        $user = User::find()->where(['openid' => $weappOpenid])->one();
        if ($user){
            if ($user->status!==1){
                return commonApi::message('禁止登陆',false);
            }
        }else{
            $user = new User();
            $user->openid = $weappOpenid;
            $user->status = 1;
            $user->unionid = $data['unionid']??'';
        }
        $user->headimgurl = $wechat['avatarUrl'];
        $user->info = json_encode($wechat);
        if ($user->save()!==false){
            $jwt = new JwtApi(self::$jwtId);
            $token = $jwt->getToken($user->id);
            return commonApi::message('登陆成功',true,[
                'nickname'=>$wechat['nickName'],
                'headimgurl'=>$wechat['avatarUrl'],
                'token'=>$token,
            ]);
        }
        return commonApi::message(commonApi::getModelError($user),false);
    }


}